package org.example.project.viewmodel

import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.datetime.Clock
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import org.example.project.model.FeeRecord

/**
 * 费用管理视图模型
 */
class FeeViewModel : ViewModel() {
    // 费用记录列表
    private val _feeRecords = MutableStateFlow<List<FeeRecord>>(emptyList())
    val feeRecords: StateFlow<List<FeeRecord>> = _feeRecords.asStateFlow()
    
    // 创建CoroutineScope用于stateIn操作符
    private val viewModelScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
    
    // 按班级分组的费用记录
    val feeRecordsByClass: StateFlow<Map<String, List<FeeRecord>>> = _feeRecords.map { records ->
        records.groupBy { it.className }
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = emptyMap()
    )

    // 当前日期
    val currentDate: LocalDate
        get() {
            val now = Clock.System.now()
            val localDateTime = now.toLocalDateTime(TimeZone.currentSystemDefault())
            return localDateTime.date
        }

    /**
     * 添加费用记录
     */
    fun addFeeRecord(record: FeeRecord) {
        _feeRecords.update { currentList ->
            currentList + record
        }
    }

    /**
     * 删除费用记录
     */
    fun deleteFeeRecord(recordId: String) {
        _feeRecords.update { currentList ->
            currentList.filter { it.id != recordId }
        }
    }

    /**
     * 计算总金额
     */
    fun calculateTotalAmount(): Double {
        return _feeRecords.value.sumOf { it.amount }
    }
    
    /**
     * 计算指定班级的总金额
     */
    fun calculateClassTotalAmount(className: String): Double {
        return _feeRecords.value
            .filter { it.className == className }
            .sumOf { it.amount }
    }
}